package com.jason.schedulemigrationtest.service.impl;

import com.jason.schedulemigrationtest.mapper.ExpressOrderHistoryMapper;
import com.jason.schedulemigrationtest.mapper.ExpressOrderMapper;
import com.jason.schedulemigrationtest.po.ExpressOrder;
import com.jason.schedulemigrationtest.service.ExpressOrderQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ExpressOrderQueryServiceImpl implements ExpressOrderQueryService {

    @Value("${data.migration.days-ago:90}")
    private int intervalDays;

    @Resource
    private ExpressOrderMapper expressOrderMapper;
    
    @Resource
    private ExpressOrderHistoryMapper expressOrderHistoryMapper;

    /**
     * 订单号查询路由
     * @param orderId 订单号
     * @return
     */
    @Override
    public ExpressOrder queryByOrderId(Long orderId) {
        log.info("查询订单号: {}", orderId);
        
        // 先查询热数据（express_order表）
        ExpressOrder order = expressOrderMapper.queryByOrderId(orderId);
        if (order != null) {
            log.info("在热数据中找到订单: {}", orderId);
            return order;
        }
        
        // 如果热数据中没有，再查询冷数据（express_order_history表）
        order = expressOrderHistoryMapper.queryByOrderId(orderId);
        if (order != null) {
            log.info("在冷数据中找到订单: {}", orderId);
            return order;
        }
        
        log.info("订单号 {} 未找到", orderId);
        return null;
    }

    /**
     * 时间范围查询路由
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @Override
    public List<ExpressOrder> queryByTimeRange(String startTime, String endTime) {
        log.info("查询时间范围: {} 到 {}", startTime, endTime);
        
        // 计算cutoff时间
        String cutoff = LocalDate.now(ZoneId.of("Asia/Shanghai"))
                .minusDays(intervalDays)
                .format(DateTimeFormatter.ISO_LOCAL_DATE);
        
        List<ExpressOrder> result = new ArrayList<>();
        
        // 判断查询时间范围与cutoff的关系
        if (startTime.compareTo(cutoff) >= 0) {
            // 查询时间都在cutoff之后，只查热数据
            log.info("查询时间范围在cutoff({})之后，只查询热数据", cutoff);
            result = expressOrderMapper.queryByTimeRange(startTime, endTime);
        } else if (endTime.compareTo(cutoff) < 0) {
            // 查询时间都在cutoff之前，只查冷数据
            log.info("查询时间范围在cutoff({})之前，只查询冷数据", cutoff);
            result = expressOrderHistoryMapper.queryByTimeRange(startTime, endTime);
        } else {
            // 查询时间跨越cutoff，需要查询两个表并聚合
            log.info("查询时间范围跨越cutoff({})，需要聚合热冷数据", cutoff);
            
            // 查询热数据（cutoff之后的数据）
            List<ExpressOrder> hotData = expressOrderMapper.queryByTimeRange(cutoff, endTime);
            log.info("热数据查询结果: {} 条", hotData.size());
            
            // 查询冷数据（cutoff之前的数据）
            List<ExpressOrder> coldData = expressOrderHistoryMapper.queryByTimeRange(startTime, cutoff);
            log.info("冷数据查询结果: {} 条", coldData.size());
            
            // 聚合结果
            result.addAll(hotData);
            result.addAll(coldData);
            
            // 按创建时间倒序排序
            result.sort((o1, o2) -> o2.getCreatedTime().compareTo(o1.getCreatedTime()));
        }
        
        log.info("时间范围查询完成，共找到 {} 条记录", result.size());
        return result;
    }
}